//
//  IG_iGameMoreViewController.m
//  iGameApp
//
//  Created by Yf66 on 16/1/12.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IG_iGameMoreViewController.h"

@interface IG_iGameMoreViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation IG_iGameMoreViewController

- (void)viewWillAppear:(BOOL)animated {
    IGRightTabBarController *tabBarController = (IGRightTabBarController *)self.navigationController.parentViewController;
    tabBarController.tabBar.hidden = YES;
    IGCustomNavigationController *navC = (IGCustomNavigationController *)self.navigationController;
    navC.iconButton.hidden = YES;
    navC.backButton.hidden = NO;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [flowLayout setItemSize:CGSizeMake((kScreenWidth - 30) / 3, (kScreenHeight - 100) / 3)];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    [_collectionView setCollectionViewLayout:flowLayout];
    // Do any additional setup after loading the view from its nib.
    [_collectionView registerNib:[UINib nibWithNibName:@"IG_iGameCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCollectionCell"];
    AppDelegate *appdelegate = [UIApplication sharedApplication].delegate;
    _context = appdelegate.managedObjectContext;
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestStart = 0;
        if (_index == -1) {
            [self setUpData];
        } else {
            [self setUpMoreData];
        }
    }];
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _requestStart += 9;
        if (_index == -1) {
            [self setUpData];
        } else {
            [self setUpMoreData];
        }
    }];
    if (_index == -1) {
         [self setUpData];
    } else {
        [self setUpMoreData];
    }
   
}

//  数据解析
- (void)setUpData {
    
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getAlbumCateList" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        NSArray *array = dataDic[@"data"];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"IGameProduct" inManagedObjectContext:_context];
        [fetchRequest setEntity:entity];
        NSError *error = nil;
        NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];
        _dataArray = [NSArray arrayWithArray:fetchedObjects];
        if (_dataArray.count == 0) {
            if (array.count != 0) {
                for (int i = 0; i < array.count ; i++) {
                    IGameProduct *product = [NSEntityDescription insertNewObjectForEntityForName:@"IGameProduct" inManagedObjectContext:_context];
                    NSDictionary *dic = array[i];
                    if (i == 0) {
                        product.album_app_image = @"bg";
                        product.album_cate_name = @"iGame";
                        product.album_cate_id = [NSNumber numberWithInteger:[dic[@"album_cate_id"] integerValue]] ;
                    } else {
                        product.album_app_image = dic[@"album_app_image"];
                        product.album_cate_name = dic[@"album_cate_name"];
                        product.album_cate_id = [NSNumber numberWithInteger:[dic[@"album_cate_id"] integerValue]] ;
                    }
                    [_context save:nil];
                }
                _dataArray = fetchedObjects;
                
            }
            
        }
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        [_collectionView reloadData];
        }
         error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}

- (void)setUpMoreData {
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *newUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getAlbumList?album_cate_id=%ld",_index];
    parDic[@"num"] = @"9";
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    [IGAFNetworking requestWithUrlString:newUrl parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        if (_requestStart == 0) {
            [_nDataArray removeAllObjects];
        }
        NSArray *array = dataDic[@"data"];
        NSString *code = dataDic[@"code"];
        if ([code isEqualToString:@"400"]) {
            [_collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            if (array.count != 0) {
                
                if (_nDataArray.count == 0) {
                    _nDataArray = [NSMutableArray array];
                }
                for (NSDictionary *dic in array) {
                    IG_iGameCollectionModel *model = [[IG_iGameCollectionModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [_nDataArray addObject:model];
                }
                [_collectionView.mj_footer endRefreshing];
                [_collectionView.mj_header endRefreshing];
                }
        [_collectionView reloadData];
    }
    }error:^(NSError *requestError) {
        NSLog(@"请求失败");
    }];
}


#pragma mark -- collcetionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_index == -1) {
        return _dataArray.count;
    }
    else {
        return _nDataArray.count;
    }

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IG_iGameCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCollectionCell" forIndexPath:indexPath];
    if (_index == -1) {
        IGameProduct *product = _dataArray[indexPath.row];
        cell.product = product;
    } else {
        IG_iGameCollectionModel *model = _nDataArray[indexPath.row];
        cell.model = model;
    }
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_index == -1) {
        IG_iGameMoreViewController *iGameMoreVC = [[IG_iGameMoreViewController alloc] init];
        IGameProduct *product = _dataArray[indexPath.row];
        iGameMoreVC.index = [product.album_cate_id integerValue];
        [self.navigationController pushViewController:iGameMoreVC animated:YES];
    } else {
        IG_CollectionViewDetailController *detailVC = [[IG_CollectionViewDetailController alloc] init];
        IG_iGameCollectionModel *model = _nDataArray[indexPath.row];
        detailVC.album_id = model.album_idStr;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
